package edu.buffalo.cse.cse486_586.simpledynamo.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.net.ServerSocket;
import java.net.Socket;

import android.util.Log;
import edu.buffalo.cse.cse486_586.simpledynamo.util.AppUtil;

public class ListeningThread implements Runnable {
	// Debug params
	final private String TAG = "ListeningThread";
	// final private Boolean isDebug = true;
	// Network properties
	private NetWorkService ns;
	private ServerSocket ss;
		
	public ListeningThread(NetWorkService ns) {
		this.ns = ns;
	}

	@Override
	public void run() {
		try {
			ss = new ServerSocket(AppUtil.PORT);
			while (this.ns.isListenThreadFlag()) {
				Socket s = ss.accept();
				if (s != null) {
					String pkg = read(s);
					Log.d(TAG, "Recieve ===>" + pkg);
					s.close();
					// We need call function to process reieved package
					ns.processReceivedContent(pkg);
				}
			}
		} catch (IOException e) {
			Log.e(TAG, "Exception", e);
		}
	}
	
	public void releaseSocket() throws IOException{
		if( ss != null ){
			ss.close();
			ss = null;
			Log.d(TAG, "release socket");
		}
			
		
	}

	public String read(Socket s) {
		ObjectInputStream in;
		try {
			in = new ObjectInputStream(s.getInputStream());
			MyPackage p;
			p = (MyPackage) in.readObject();
			in.close();
			return p.getContent();
		} catch (StreamCorruptedException e) {
			Log.e(TAG, "Exception", e);
			return "";
		} catch (IOException e) {
			Log.e(TAG, "Exception", e);
			return "";
		} catch (ClassNotFoundException e) {
			Log.e(TAG, "Exception", e);
			return "";
		}
		
	}
}
